<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文生图 - AI图像生成</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background-color: #f5f5f5;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        header {
            text-align: center;
            margin-bottom: 30px;
            padding: 20px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        h1 {
            color: #333;
            font-size: 2rem;
            margin-bottom: 10px;
        }

        .subtitle {
            color: #666;
            font-size: 1.1rem;
        }

        .content {
            background: white;
            border-radius: 10px;
            padding: 30px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            text-align: center;
        }

        .prompt-input {
            width: 80%;
            padding: 12px;
            font-size: 1rem;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin: 20px 0;
        }

        .checkbox-container {
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 10px 0;
        }

        .checkbox-container input {
            margin-right: 8px;
        }

        .interval-container {
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 10px 0;
        }

        .interval-container label {
            margin-right: 10px;
        }

        .interval-container input {
            width: 60px;
            padding: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .progress-container {
            width: 80%;
            margin: 20px auto;
            display: none;
        }

        .progress-bar {
            width: 100%;
            height: 20px;
            background-color: #f0f0f0;
            border-radius: 10px;
            overflow: hidden;
        }

        .progress-fill {
            height: 100%;
            background-color: #4CAF50;
            width: 0%;
            transition: width 0.3s ease;
        }

        .progress-text {
            margin-top: 5px;
            font-size: 0.9rem;
            color: #666;
        }

        .image-container {
            margin: 20px 0;
        }

        #generated-image {
            max-width: 100%;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            display: none;
        }

        .loading {
            display: none;
            font-size: 1.2rem;
            color: #666;
            margin: 20px 0;
        }

        .error {
            color: #e74c3c;
            margin: 20px 0;
            display: none;
        }

        .btn {
            background-color: #4CAF50;
            border: none;
            color: white;
            padding: 12px 24px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin: 10px 2px;
            cursor: pointer;
            border-radius: 4px;
            transition: background-color 0.3s;
        }

        .btn:hover {
            background-color: #45a049;
        }

        .btn:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }

        .btn-stop {
            background-color: #f44336;
        }

        .btn-stop:hover {
            background-color: #d32f2f;
        }

        @media (max-width: 768px) {
            body {
                padding: 10px;
            }
            
            h1 {
                font-size: 1.5rem;
            }
            
            .subtitle {
                font-size: 1rem;
            }
            
            .content {
                padding: 20px;
            }
            
            .prompt-input, .progress-container {
                width: 95%;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>文生图 - AI图像生成</h1>
            <p class="subtitle">将文字描述转换为精美的图像</p>
        </header>
        
        <main class="content">
            <input type="text" id="prompt-input" class="prompt-input" placeholder="请输入图片描述，例如：一只猫" value="一只猫">
            
            <div class="checkbox-container">
                <input type="checkbox" id="continuous-checkbox" checked>
                <label for="continuous-checkbox">连续生成</label>
            </div>
            
            <div class="interval-container">
                <label for="interval-input">间隔时间（秒）：</label>
                <input type="number" id="interval-input" min="10" max="300" value="60">
            </div>
            
            <div class="button-container">
                <button id="generate-btn" class="btn">生成图片</button>
                <button id="stop-btn" class="btn btn-stop" style="display: none;">停止生成</button>
            </div>
            
            <div class="progress-container" id="progress-container">
                <div class="progress-bar">
                    <div class="progress-fill" id="progress-fill"></div>
                </div>
                <div class="progress-text" id="progress-text">正在启动任务...</div>
            </div>
            
            <div class="loading" id="loading">
                正在生成图片，请稍候...
            </div>
            
            <div class="error" id="error">
                <!-- 错误信息将在这里显示 -->
            </div>
            
            <div class="image-container">
                <img id="generated-image" alt="AI生成的图片">
            </div>
            
            <div class="image-container">
                <img id="generated-image" alt="AI生成的图片">
            </div>
        </main>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const promptInput = document.getElementById('prompt-input');
            const continuousCheckbox = document.getElementById('continuous-checkbox');
            const intervalInput = document.getElementById('interval-input');
            const generateBtn = document.getElementById('generate-btn');
            const stopBtn = document.getElementById('stop-btn');
            const progressContainer = document.getElementById('progress-container');
            const progressFill = document.getElementById('progress-fill');
            const progressText = document.getElementById('progress-text');
            const loadingElement = document.getElementById('loading');
            const errorElement = document.getElementById('error');
            const imageElement = document.getElementById('generated-image');
            
            // 控制变量
            let isGenerating = false;
            let currentAbortController = null;
            let countdownInterval = null;
            
            generateBtn.addEventListener('click', generateImage);
            stopBtn.addEventListener('click', stopGeneration);
            
            async function generateImage() {
                const prompt = promptInput.value.trim();
                
                if (!prompt) {
                    alert('请输入图片描述');
                    return;
                }
                
                const isContinuous = continuousCheckbox.checked;
                
                if (isContinuous) {
                    // 连续生成模式
                    generateContinuously(prompt);
                } else {
                    // 单次生成模式
                    generateOnce(prompt);
                }
            }
            
            async function generateOnce(prompt) {
                // 初始化控制变量
                isGenerating = true;
                
                // 显示停止按钮，隐藏生成按钮
                generateBtn.style.display = 'none';
                stopBtn.style.display = 'inline-block';
                
                // 初始化进度条
                progressContainer.style.display = 'block';
                progressFill.style.width = '0%';
                const startTime = Date.now();
                progressText.textContent = '正在启动任务...';
                errorElement.style.display = 'none';
                
                // 创建AbortController用于取消请求
                currentAbortController = new AbortController();
                
                try {
                    // 1. 启动图片生成任务
                    const startResponse = await fetch(`/api/start-image-generation?prompt=${encodeURIComponent(prompt)}`, {
                        signal: currentAbortController.signal
                    });
                    const startData = await startResponse.json();
                    
                    if (!startData.success) {
                        throw new Error(startData.error);
                    }
                    
                    const taskId = startData.taskId;
                    progressText.textContent = '任务已启动，正在处理中...';
                    
                    // 2. 轮询任务状态
                    let attempts = 0;
                    const maxAttempts = 60;
                    const pollInterval = 5000; // 5秒
                    
                    while (attempts < maxAttempts && isGenerating) {
                        attempts++;
                        const elapsedSeconds = Math.floor((Date.now() - startTime) / 1000);
                        // 更直观地显示进度百分比和已用时间
                        const progressPercent = Math.min(Math.round((attempts / maxAttempts) * 100), 95);
                        progressFill.style.width = `${progressPercent}%`;
                        progressText.textContent = `正在处理中... ${progressPercent}% (已用时 ${elapsedSeconds} 秒)`;
                        
                        // 等待一段时间再检查状态
                        await new Promise(resolve => setTimeout(resolve, pollInterval));
                        
                        if (!isGenerating) {
                            // 用户已停止生成
                            return;
                        }
                        
                        try {
                            const statusResponse = await fetch(`/api/check-task-status?taskId=${taskId}`, {
                                signal: currentAbortController.signal
                            });
                            const statusData = await statusResponse.json();
                            
                            if (statusData.success) {
                                // 任务完成
                                const totalElapsedSeconds = Math.floor((Date.now() - startTime) / 1000);
                                progressFill.style.width = '100%';
                                progressText.textContent = `图片生成完成！总用时 ${totalElapsedSeconds} 秒`;
                                
                                // 显示生成的图片
                                imageElement.src = statusData.imageUrl;
                                imageElement.style.display = 'block';
                                return;
                            } else if (statusData.error) {
                                throw new Error(statusData.error);
                            }
                        } catch (error) {
                            if (error.name === 'AbortError') {
                                // 用户取消了请求
                                return;
                            } else if (error.message.includes('timeout') || error.message.includes('Timeout')) {
                                // 继续轮询
                                continue;
                            } else {
                                throw error;
                            }
                        }
                    }
                    
                    // 检查是否是用户停止了生成
                    if (!isGenerating) {
                        return;
                    }
                    
                    // 超时
                    throw new Error('图片生成超时，请稍后重试');
                } catch (error) {
                    // 显示错误信息（除非是用户主动停止）
                    if (isGenerating && error.name !== 'AbortError') {
                        errorElement.textContent = '生成图片失败: ' + error.message;
                        errorElement.style.display = 'block';
                    }
                } finally {
                    // 恢复按钮状态
                    isGenerating = false;
                    stopBtn.style.display = 'none';
                    generateBtn.style.display = 'inline-block';
                    progressContainer.style.display = 'none';
                    currentAbortController = null;
                }
            }
            
            async function generateContinuously(prompt) {
                isGenerating = true;
                
                // 显示停止按钮，隐藏生成按钮
                generateBtn.style.display = 'none';
                stopBtn.style.display = 'inline-block';
                
                while (isGenerating) {
                    // 初始化进度条
                    progressContainer.style.display = 'block';
                    progressFill.style.width = '0%';
                    const startTime = Date.now();
                    progressText.textContent = '正在启动任务...';
                    errorElement.style.display = 'none';
                    
                    // 创建AbortController用于取消请求
                    currentAbortController = new AbortController();
                    
                    try {
                        // 1. 启动图片生成任务
                        const startResponse = await fetch(`/api/start-image-generation?prompt=${encodeURIComponent(prompt)}`, {
                            signal: currentAbortController.signal
                        });
                        const startData = await startResponse.json();
                        
                        if (!startData.success) {
                            throw new Error(startData.error);
                        }
                        
                        const taskId = startData.taskId;
                        progressText.textContent = '任务已启动，正在处理中...';
                        
                        // 2. 轮询任务状态
                        let attempts = 0;
                        const maxAttempts = 60;
                        const pollInterval = 5000; // 5秒
                        
                        while (attempts < maxAttempts && isGenerating) {
                            attempts++;
                            const elapsedSeconds = Math.floor((Date.now() - startTime) / 1000);
                            // 更直观地显示进度百分比和已用时间
                            const progressPercent = Math.min(Math.round((attempts / maxAttempts) * 100), 95);
                            progressFill.style.width = `${progressPercent}%`;
                            progressText.textContent = `图片生成中... ${progressPercent}% (已用时 ${elapsedSeconds} 秒)`;
                            
                            // 等待一段时间再检查状态
                            await new Promise(resolve => setTimeout(resolve, pollInterval));
                            
                            if (!isGenerating) {
                                // 用户已停止生成
                                return;
                            }
                            
                            try {
                                const statusResponse = await fetch(`/api/check-task-status?taskId=${taskId}`, {
                                    signal: currentAbortController.signal
                                });
                                const statusData = await statusResponse.json();
                                
                                if (statusData.success) {
                                    // 任务完成
                                    const totalElapsedSeconds = Math.floor((Date.now() - startTime) / 1000);
                                    progressFill.style.width = '100%';
                                    progressText.textContent = `图片生成完成！总用时 ${totalElapsedSeconds} 秒`;
                                    
                                    // 显示生成的图片（替换上一张图片）
                                    imageElement.src = statusData.imageUrl;
                                    imageElement.style.display = 'block';
                                    progressContainer.style.display = 'none';
                                    break; // 跳出轮询循环，开始下一次生成
                                } else if (statusData.error) {
                                    throw new Error(statusData.error);
                                }
                            } catch (error) {
                                if (error.name === 'AbortError') {
                                    // 用户取消了请求
                                    return;
                                } else if (error.message.includes('timeout') || error.message.includes('Timeout')) {
                                    // 继续轮询
                                    continue;
                                } else {
                                    throw error;
                                }
                            }
                        }
                        
                        // 检查是否是用户停止了生成
                        if (!isGenerating) {
                            return;
                        }
                        
                        if (attempts >= maxAttempts) {
                            // 超时
                            throw new Error('图片生成超时，请稍后重试');
                        }
                        
                        // 等待用户设定的时间间隔再开始下一次生成
                        if (isGenerating) {
                            const interval = parseInt(intervalInput.value) || 60;
                            progressText.textContent = `等待 ${interval} 秒后开始下一次生成...`;
                            progressContainer.style.display = 'block';
                            
                            // 倒计时显示
                            let countdown = interval;
                            countdownInterval = setInterval(() => {
                                progressText.textContent = `等待 ${countdown} 秒后开始下一次生成...`;
                                countdown--;
                                
                                if (countdown < 0 || !isGenerating) {
                                    clearInterval(countdownInterval);
                                    countdownInterval = null;
                                }
                            }, 1000);
                            
                            // 等待指定时间
                            await new Promise(resolve => {
                                const waitTimeout = setTimeout(resolve, interval * 1000);
                                // 如果用户停止生成，则立即resolve
                                const checkInterval = setInterval(() => {
                                    if (!isGenerating) {
                                        clearTimeout(waitTimeout);
                                        clearInterval(checkInterval);
                                        resolve();
                                    }
                                }, 100);
                            });
                        }
                    } catch (error) {
                        // 显示错误信息（除非是用户主动停止）
                        if (isGenerating && error.name !== 'AbortError') {
                            errorElement.textContent = '生成图片失败: ' + error.message;
                            errorElement.style.display = 'block';
                            progressContainer.style.display = 'none';
                        }
                        break; // 出错时停止生成
                    } finally {
                        // 清理AbortController
                        currentAbortController = null;
                        
                        // 清理倒计时
                        if (countdownInterval) {
                            clearInterval(countdownInterval);
                            countdownInterval = null;
                        }
                    }
                }
                
                // 恢复按钮状态
                stopBtn.style.display = 'none';
                generateBtn.style.display = 'inline-block';
                progressContainer.style.display = 'none';
                isGenerating = false;
            }
            
            function stopGeneration() {
                isGenerating = false;
                
                // 如果有正在进行的请求，取消它
                if (currentAbortController) {
                    currentAbortController.abort();
                }
                
                // 清理倒计时
                if (countdownInterval) {
                    clearInterval(countdownInterval);
                    countdownInterval = null;
                }
                
                // 隐藏停止按钮，显示生成按钮
                stopBtn.style.display = 'none';
                generateBtn.style.display = 'inline-block';
                progressContainer.style.display = 'none';
            }
        });
    </script>
</body>
</html>